<template>
  <div>
    <van-nav-bar title="编辑地址" left-arrow @click-left="$router.back()">
      <template #right>
        <van-icon name="ellipsis" />
      </template>
    </van-nav-bar>
    <van-address-edit
      :area-list="areaList"
      :address-info="AddressInfo"
      show-postal
      show-delete
      show-set-default
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import { Toast } from "vant";
import { APIgetAddressDetail, APIeditAddress,APIdelAddress } from "@/http/index.js";
import Vue from "vue";
import { areaList } from "@vant/area-data";
import { AddressEdit } from "vant";

Vue.use(AddressEdit);

export default {
  name: "AddressEdit",
  props: [],
  data() {
    return {
      areaList: Object.freeze(areaList),
      AddressInfo: {},
    };
  },
  mounted() {
    //console.log(this.$route)
    APIgetAddressDetail(this.$route.params.addressId).then((res) => {
      //console.log(res)
      if (res.resultCode == 200) {
        let {
          addressId,
          cityName,
          defaultFlag,
          detailAddress,
          provinceName,
          regionName,
          userName,
          userPhone,
        } = res.data;

        this.AddressInfo = {
          id: addressId,
          addressDetail: detailAddress,
          city: cityName,
          county: regionName,
          isDefault: Boolean(defaultFlag),
          name: userName,
          province: provinceName,
          tel: userPhone,
          postalCode: "100000",
          // 给你一个地址，需要得这个地区的编码
          areaCode: this.getAreaCode(regionName),
        };
      }
    });
  },
  methods: {
    // 根据地址，得到地区编码
    getAreaCode(area) {
      area = area.replace(/区|县/, "");
      for (let k in areaList.county_list) {
        if (areaList.county_list[k].includes(area)) {
          return k;
        }
      }
    },
    onSave(val) {
      //console.log(val);
      let {id,city,isDefault,addressDetail,province,county,name,tel,areaCode,postalCode} = val;
      let editObj = {
        addressId: id,
        cityName: city,
        defaultFlag: isDefault? 1:0,
        detailAddress: addressDetail,
        provinceName: province,
        regionName: county,
        userName: name,
        userPhone: tel,
        areaCode,
        postalCode,
      };
      APIeditAddress(editObj).then(res=>{
          //console.log(res)
          if(res.resultCode==200){
            Toast("修改地址成功");
            this.$router.push("/addressList")
          }
      })
    },
    onDelete(val) {
      //console.log(val)
      APIdelAddress(val.id).then(res=>{
        if(res.resultCode==200){
            Toast("删除地址成功");
            this.$router.push("/addressList")
          }
      })
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less"></style>
